<template>
  <div>
    <canvas id="myCanvas" width="400" height="300"></canvas>
    <button @click="isDrawing = true">马赛克</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      isDrawing: false,
    };
  },
  mounted() {
    const image = new Image();
    image.src = require("@/assets/masaike.jpg"); // 替换为你想要绘制的图片的URL
    image.addEventListener("load", () => {
      this.init();
      this.ctx.drawImage(image, 0, 0, this.canvas.width, this.canvas.height);
    });
  },
  methods: {
    init() {
      this.canvas = document.getElementById("myCanvas");
      this.ctx = this.canvas.getContext("2d");
      this.isDrawing = false;
      this.canvas.addEventListener("mousemove", (e) => {
        if (this.isDrawing) {
          const rect = this.canvas.getBoundingClientRect();
          const x = e.clientX - rect.left;
          const y = e.clientY - rect.top;
          this.drawMosaic(x, y);
        }
      });
    },
    drawMosaic(x, y) {
      const mosaicSize = 20; // 马赛克块的大小
      const imageData = this.ctx.getImageData(
        x - mosaicSize / 2,
        y - mosaicSize / 2,
        mosaicSize,
        mosaicSize
      );
      // 获取马赛克块内的第一个像素值
      const r = imageData.data[0];
      const g = imageData.data[1];
      const b = imageData.data[2];

      // 将马赛克块内的所有像素值设置为第一个像素值，实现马赛克效果
      for (let i = 0; i < imageData.data.length; i += 4) {
        imageData.data[i] = r;
        imageData.data[i + 1] = g;
        imageData.data[i + 2] = b;
      }
      this.ctx.putImageData(imageData, x - mosaicSize / 2, y - mosaicSize / 2);
    },
  },
};
</script>

<style lang="scss" scoped></style>
